import { createStore } from 'vuex'
import { alert } from '../utils/alert';
import {post, get, fetch} from '@/utils/axios.js';
import properties from '@/properties.js';

export default createStore({
	state: {
		// user
		isLogin: false,
		ifNewMessage: true,
		user: {
			infos: {},
			works: {
				article: [],
				source: [],
			},
			collection: {
				article: [],
				source: []
			},
			history: {
				article: [],
				source: [],
			},
			worksPage: {
				article: 0,
				source: 0,
			},
			collectionPage: {
				article: 0,
				source: 0
			},
			historyPage: {
				article: 0,
				source: 0,
			}
		},

		// utils
		educationNames: [],
		universityNames: [],
		typeNames: [],
		tagNames: [],
	},
	getters: {
		userBaseInfos(state) {
			let baseInfoKeyList = ['username', 'nickname', 'sex', 'sign',
			'birthday', 'location', 'education', 'university'];
			let userInfos = state.user.infos;
			let obj = {};
			Object.keys(userInfos).forEach(key => {
				if(baseInfoKeyList.includes(key)) obj[key] = userInfos[key];
			});
			return obj;
		},
		userAccountInfos(state) {
			let accountUserInfoKeyList = ['email', 'userpwd'];
			let userInfos = state.user.infos;
			let obj = {};
			Object.keys(userInfos).forEach(key => {
				if(accountUserInfoKeyList.includes(key)) obj[key] = userInfos[key];
			});
			return obj;
		}
	},
	mutations: {
		// user realted
		welcome(state) {
			get({
				url: 'welcome',
				name: 'welcome'
			}).then((res) => {
				if(res.data.success) {
					state.isLogin = true;
					window.sessionStorage.setItem('isLogin', true);
					this.commit('fetchUserInfos');
				} else {
					console.log('welcome: auto login fail');
				}
			})
			this.commit('fetchUniversityNames');
			this.commit('fetchEducationNames');
			this.commit('fetchTagNames');
			this.commit('fetchTypeNames');
		},
		login(state, payload) {
			let infos = payload.infos,
				cb = payload.callback;

			post({
				url: 'login',
				data: infos,
				name: 'login'
			}).then((response) => {
				if(response.data.success) {
					state.isLogin = true;
					window.sessionStorage.setItem('isLogin', true);
					alert('登录成功');
					this.commit('fetchUserInfos');
					if(typeof cb === 'function') cb(true);
				} else {
					alert({
						type: 'error',
						content: '登录失败'
					});
					if(typeof cb === 'function') cb(false);
				}
			}).catch(error => {
				alert({
					type: 'error',
					content: '登录失败'
				});
				if(typeof cb === 'function') cb(false);
			})
		},
		register(state, payload) {
			let infos = payload.infos;
			let cb = payload.callback;
			post({
				name: 'register',
				url: 'register/sendmail',
				data: infos
			}).then((response) => {
				if(response.data.success) {
					alert("请查收邮箱激活账号");
					if(typeof cb === 'function') cb(true);
				} else {
					alert({
						type: 'error',
						content: '注册失败'
					});
					if(typeof cb === 'function') cb(false);
				}
			}).catch(error => {
				alert({
					type: 'error',
					content: '注册失败'
				});
				if(typeof cb === 'function') cb(false);
			})
		},
		logout() {
			get({
				name: 'logout',
				url: 'logout'
			}).then(() => {
				window.sessionStorage.removeItem('isLogin');
				window.open(properties.$routeBaseURL + "/", '_self');
			})
		},
		fetchUserInfos(state) {
			get({
				name: 'userInfo',
				url: 'user/info/content'
			}).then((res) => {
				if(res.data.success) {
					let info = res.data.object;
					info.work_num = info.article_num + info.source_num + info.column_num;
					state.user.infos = info;
				} else {
					alert({
						type: 'error', 
						content: '获取用户信息失败'
					});
				}
			})
		},
		changeBaseInfo(state, kvp) {
			post({
				name: 'change base info',
				url: 'user/info/edit/normal',
				data: {
					[kvp.key]: kvp.value
				}
			}).then(res => {
				if(res.data.success) {
					alert('更改成功！');
					this.commit('fetchUserInfos');
				} else {
					alert({
						type: 'error', 
						content: '更改信息失败'
					});
				}
			}).catch(error => {
				alert({
					type: 'error', 
					content: '更改信息失败'
				});
			})
		},
		changeAccountInfo(state, kvp) {
			if(kvp.key === 'userpwd') {
				let data = {
					userpwd: kvp.value,
				};
				if(kvp.oldpwd) data.oldpwd = kvp.oldpwd;
				post({
					name: 'edit password',
					url: 'user/info/edit/userpwd',
					data
				}).then(res => {
					if(res.data.success) {
						alert(res.data.message, () => {
							this.commit('logout');
						})
					} else {
						alert({
							type: false,
							content: '修改失败，请重试'
						})
					}
				}).catch(error => {
					alert({
						type: false,
						content: '修改失败，请重试'
					})
				})
			} else if (kvp.key === 'email') {
				post({
					name: 'edit email',
					url: 'user/info/edit/email',
					data: {
						email: kvp.value,
						userpwd: kvp.userpwd
					},
					callback: res => {
						if(res.data.success) {
							alert(res.data.message, () => {
								this.commit('logout');
							})
						} else {
							alert({
								type: 'error',
								content: '修改失败，请重试'
							})
						}
					}
				})
			}
		},
		changePwd(state, payload) {
			let info = payload.info;
			let cb = payload.callback;
			post({
				name: 'check findpwd verification',
				url: 'findpwd/changepwd',
				data: {
					...info
				}
			}).then(res => {
				if(res.data.success) {
					alert("密码修改成功!");
					if(typeof cb === 'function') cb(true);
				}
				else {
					alert({
						type: 'error',
						content: res.data.message
					})
					if(typeof cb === 'function') cb(false);
				}
			}).catch(error => {
				alert({
					type: 'error',
					content: res.data.message
				})
				if(typeof cb === 'function') cb(false);
			})
		},

		// utils
		fetchUniversityNames(state) {
			get({
				name: 'university names',
				url: 'util/university/names'
			}).then(res => {
				if(res.data.success) {
					state.universityNames = res.data.object;
				}
			})
		},
		fetchEducationNames(state) {
			get({
				name: 'education names',
				url: 'util/education/names'
			}).then(res => {
				if(res.data.success) {
					state.educationNames = res.data.object;
				}
			})
		},
		fetchTypeNames(state) {
			get({
				name: 'type names',
				url: 'util/type/names'
			}).then(res => {
				if(res.data.success) {
					state.typeNames = res.data.object;
				}
			})
		},
		fetchTagNames(state) {
			get({
				name: 'tag names',
				url: 'util/tag/names'
			}).then(res => {
				if(res.data.success) {
					state.tagNames = res.data.object;
				}
			})
		},

		// aritcle source related

		fetchHistoryArticleAbstracts(state) {
			fetch({
				name: 'user history article',
				url: 'user/browse/history/article',
				method: 'POST',
				data: {
					page: ++state.user.historyPage.article
				}
			}).then(res => {
				if(res.data.success && res.data.object.length) {
					state.user.history.article = state.user.history.article.concat(res.data.object);
				} else {
					state.user.historyPage.article--;
				}
			}).catch(error => {
				alert({
					type: 'error',
					content: '获取文章浏览历史失败'
				});
				state.user.historyPage.article--;
			})
		},
    fetchWorksArticleAbstracts(state) {
			fetch({
				name: 'user article',
				url: 'user/works/article',
				method: 'POST',
				data: {
					page: ++state.user.worksPage.article
				}
			}).then(res => {
				if(res.data.success && res.data.object.length) {
					state.user.works.article = state.user.works.article.concat(res.data.object);
				} else {
					state.user.worksPage.article--;
				}
			}).catch(error => {
				alert({
					type: 'error',
					content: '获取文章作品信息失败'
				});
				state.user.worksPage.article--;
			})
    },
    fetchCollectionArticleAbstracts(state) {
			fetch({
				name: 'user collection',
				url: 'user/collection/article',
				method: 'POST',
				data: {
					page: ++state.user.collectionPage.article
				}
			}).then(res => {
				if(res.data.success && res.data.object.length) {
					state.user.collection.article = state.user.collection.article.concat(res.data.object);
				} else {
					state.user.collectionPage.article--;
				}
			}).catch(error => {
				alert({
					type: 'error',
					content: '获取文章收藏失败'
				})
				state.user.collectionPage.article--;
			})
    },

		fetchHistorySourceAbstracts(state) {
			fetch({
				name: 'user history source',
				url: 'user/browse/history/source',
				method: 'POST',
				data: {
					page: ++state.user.historyPage.source
				}
			}).then(res => {
				if(res.data.success && res.data.object.length) {
					state.user.history.source = state.user.history.source.concat(res.data.object);
				} else {
					state.user.historyPage.source--;
				}
			}).catch(error => {
				alert({
					type: 'error',
					content: '获取资源浏览历史失败'
				});
				state.user.historyPage.source--;
			})
		},
    fetchWorksSourceAbstracts(state) {
			fetch({
				name: 'user source',
				url: 'user/works/source',
				method: 'POST',
				data: {
					page: ++state.user.worksPage.source
				}
			}).then(res => {
				if(res.data.success && res.data.object.length) {
					state.user.works.source = state.user.works.source.concat(res.data.object);
				} else {
					state.user.worksPage.source--;
				}
			}).catch(error => {
				alert({
					type: 'error',
					content: '获取资源作品失败'
				});
				state.user.worksPage.source--;
			})
    },
    fetchCollectionSourceAbstracts(state) {
			fetch({
				name: 'user collection source',
				url: 'user/collection/source',
				method: 'POST',
				data: {
					page: ++state.user.collectionPage.source
				}
			}).then(res => {
				if(res.data.success && res.data.object.length) {
					state.user.collection.source = state.user.collection.source.concat(res.data.object);
				} else {
					state.user.collectionPage.source--;
				}
			}).catch(error => {
				alert({
					type: 'error',
					content: '获取资源收藏失败'
				});
				state.user.collectionPage.source--;
			})
    },
		cleanHistoryArticle(state) {
			get({
				name: 'clean history article',
				url: 'user/browse/history/article/clean'
			}).then(res => {
				if(res.data.success) {
					alert("清空文章历史记录成功");
					state.user.history.article = [];
				} else {
					alert({
						type: 'error',
						content: '清空文章历史记录失败'
					})
				}
			}).catch(error => {
				alert({
					type: 'error',
					content: '清空文章历史记录失败'
				})
			})
		},
		cleanHistorySource(state) {
			get({
				name: 'clean history source',
				url: 'user/browse/history/source/clean'
			}).then(res => {
				if(res.data.success) {
					alert("清空资源历史记录成功");
					state.user.history.source = [];
				} else {
					alert({
						type: 'error',
						content: "清空资源历史记录失败"
					})
				}
			}).catch(() => {
				alert({
					type: 'error',
					content: "清空资源历史记录失败"
				})
			})
		},

		renewHistorySourceAbstracts(state) {
			state.user.historyPage.source = 0;
			state.user.history.source = [];
			this.commit('fetchHistorySourceAbstracts');
		},
		renewHistoryArticleAbstracts(state) {
			state.user.historyPage.article = 0;
			state.user.history.article = [];
			this.commit('fetchHistoryArticleAbstracts');
		},
	},
})